﻿using System;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;

namespace YJKArch.AxisModule
{
	public class RemoveAixs
	{
		public RemoveAixs(ExternalCommandData cmdData)
		{
			this.m_Revit = cmdData;
		}

		public Result Remove(ref string message)
		{
			Result result;
			try
			{
				Element element = this.SelectGrid();
				if (element == null)
				{
					throw new System.ArgumentNullException("isn't aixs");
				}
				this.Delete(element);
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}

		private Element SelectGrid()
		{
			Selection selection = this.m_Revit.Application.ActiveUIDocument.Selection;
			try
			{
				AxisFilter axisFilter = new AxisFilter();
				Reference reference = selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, axisFilter, "选择轴线");
				Element element = this.m_Revit.Application.ActiveUIDocument.Document.GetElement(reference);
				if (element.GetType() == typeof(MultiSegmentGrid) || element.GetType() == typeof(Grid))
				{
					return element;
				}
			}
			catch (Exception)
			{
				return null;
			}
			return null;
		}

		private void Delete(Element grid)
		{
			string name = grid.Name;
			new AxisNameManager(this.m_Revit).RemoveName(name);
			this.m_Revit.Application.ActiveUIDocument.Document.Delete(grid.Id);
			this.m_Revit.Application.ActiveUIDocument.Document.Regenerate();
		}

		protected ExternalCommandData m_Revit;
	}
}
